package net.towee.client.widgets.upload.impl;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import net.towee.client.widgets.ExtFlowPanel;
import net.towee.client.widgets.upload.UploadForm;
import net.towee.client.widgets.upload.UploadItem;
import net.towee.client.widgets.upload.UploadStartHandler;

import com.google.gwt.event.dom.client.DropEvent;
import com.google.gwt.event.shared.HandlerRegistration;

public abstract class AbstractUploadForm extends ExtFlowPanel implements UploadForm {
	protected final List<UploadStartHandler> handlers = new ArrayList<UploadStartHandler>();
	
	protected final List<UploadItem> uploadItems = new ArrayList<UploadItem>();
	protected final Queue<UploadItem> uploadQueue = new LinkedList<UploadItem>();
	protected int uploadingPoolSize = 0;
	
	protected long globalTotalSize = 0;
	protected long globalLoadedSize = 0;
	
	protected int filesLimit = 30;
	protected long maxFileSize = 10008902;

	/**
	 * Invoked when some file uploaded. It start uploading next
	 * file in queue.
	 */
	protected void freeQueue() {
		uploadingPoolSize--;
		UploadItem item = uploadQueue.poll();
		
		if(item != null)
			item.start();
	}
	
	@Override
	public HandlerRegistration addUploadStartHandler(final UploadStartHandler handler) {
		handlers.add(handler);
		
		return new HandlerRegistration(){
			@Override
			public void removeHandler() {
				handlers.remove(handler);
			}
		};
	}
	
	@Override
	public int getGlobalProgress() {
		return (int)((globalLoadedSize / globalTotalSize) * 100);
	}

	@Override
	public long getGlobalSize() {
		return globalTotalSize;
	}

	@Override
	public void cancelAll() {
		for(UploadItem it : uploadItems)
			if(!it.isComplited())
				it.cancel();
	}

	@Override
	public void setFilesNumberLimit(int number) {
		this.filesLimit = number;
	}

	@Override
	public void setMaxFileSize(long size) {
		this.maxFileSize = size;
	}

	@Override
	public boolean isDropSupported() {
		return DropEvent.isSupported();
	}
}
